package v1

import (
	"fmt"
	"net/http"
	"server/global"
	"server/global/e"
	"server/global/form"
	"server/global/response"
	"server/service"

	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
)

// @Summary Get Device Logs
// @Produce  json
// @Param device_id body int true "DeviceID"
// @Param page body int false "Page"
// @Param page_size body int false "PageSize"
// @Param start_time body int false "StartTime"
// @Param end_time body int false "EndTime"
// @Success 200 {object} response.Response
// @Failure 500 {object} response.Response
// @Router /api/v1/device_logs [get]
func GetDeviceLogs(c *gin.Context) {
	r := response.Gin{C: c}
	valid := validation.Validation{}

	device_id := -1
	if arg := c.Query("device_id"); arg != "" {
		device_id = com.StrTo(arg).MustInt()
		valid.Min(device_id, 1, "device_id")
	}

	page := com.StrTo(c.Query("page")).MustInt()
	page_size := com.StrTo(c.Query("page_size")).MustInt()

	start_time := c.Query("start_time")
	end_time := c.Query("end_time")

	if valid.HasErrors() {
		form.MarkErrors(valid.Errors)
		r.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
		return
	}

	maps := make(map[string]interface{})
	maps["device_id"] = device_id
	maps["page"] = page
	maps["page_size"] = page_size
	maps["start_time"] = start_time
	maps["end_time"] = end_time

	total, logs, err := service.DeviceLogFetch(maps)
	if err != nil {
		global.LOG.Error(fmt.Sprintf("%v", err))
		r.Response(http.StatusInternalServerError, -1, err)
		return
	}

	data := make(map[string]interface{})
	data["total"] = total
	data["items"] = logs

	r.Response(http.StatusOK, e.SUCCESS, data)
}
